import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/controller/schooladmin.dart';
import 'package:ichinesereader/pages/schooladmin/adminTeacherEditor.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:reactive_dropdown_search/reactive_dropdown_search.dart';
import 'package:reactive_forms/reactive_forms.dart';
import '../../models/school/moveClassStudentsDto.dart';
import '../../utils/log.dart';

// ignore: must_be_immutable
class MoveStudentToClassDialog extends StatelessWidget {
  MoveStudentToClassDialog(
      {Key? key,
      required this.userNames,
      required this.fromClassId,
      this.completeCallback})
      : super(key: key);
  List<String> userNames;
  String fromClassId;
  Function? completeCallback;
  SchoolAdminController controller = Get.find();
  var box = Hive.box('appconfig');

  FormGroup buildForm() => fb.group(<String, Object>{
        'classId': FormControl<DropdownModel>(validators: [Validators.required])
      });

  @override
  Widget build(BuildContext context) {
    Log.debug(
        "build MoveStudentToClassDialog fromClassId=${fromClassId.toString()} userNames=$userNames");
    FormGroup form = buildForm();

    List<DropdownModel> allClass = [];
    controller.classItems.forEach((element) {
      if (element.classId != fromClassId && element.classId != 'All') {
        allClass.add(DropdownModel(element.classId, element.className));
      }
    });

    bool classDropdownModelCompareFn(
        DropdownModel? item, DropdownModel? selectedItem) {
      Log.debug(
          "item=${item.toString()} selectedItem=${selectedItem.toString()}");
      return item != null && selectedItem != null && item.id == selectedItem.id;
    }

    // void showMsg(String msg) {
    //   Get.snackbar('Message'.tr, '$msg'.tr,
    //       backgroundColor: Get.theme.primaryColor,
    //       colorText: Get.theme.primaryColorLight,
    //       snackPosition: SnackPosition.BOTTOM);
    // }

    void _onUpdate() {
      Log.debug('_onUpdate form.value=${form.value}');
      if (!form.valid) {
        form.markAllAsTouched();
        return;
      }
      DropdownModel selectedClass =
          form.control('classId').value as DropdownModel;
      String toClassId = selectedClass.id.toString();
      MoveClassStudentsDto dto = new MoveClassStudentsDto();
      dto.fromClassId = fromClassId;
      dto.toClassId = toClassId;
      dto.userNameList = userNames;
      controller.moveClassStudents(dto).then((statusMessage) {
        if (statusMessage.status == 1000) {
          showSnackMsg('Successfully updated!'.tr);

          Future.delayed(const Duration(milliseconds: 1000), () {
            Navigator.of(Get.context!).pop();
            completeCallback!();
          });
        } else {
          showSnackMsg(statusMessage.message.toString());
        }
      });
    }

    void _onCancel() {
      Navigator.of(context).pop();
    }

    _buildForm() {
      List<Widget> formWidget = [];

      formWidget.add(ReactiveDropdownSearch<DropdownModel, DropdownModel>(
        formControlName: 'classId',
        dropdownDecoratorProps: DropDownDecoratorProps(
          dropdownSearchDecoration: InputDecoration(
            hintText: "Select class".tr,
            labelText: "Class".tr,
          ),
        ),
        //popupBackgroundColor: Colors.white,
        popupProps: PopupPropsMultiSelection.menu(
            showSelectedItems: true, showSearchBox: true),
        //mode: Mode.DIALOG,
        // hint: 'Select a class',
        compareFn: (item, selectedItem) =>
            classDropdownModelCompareFn(item, selectedItem),
        // showSelectedItems: true,
        items: allClass,
        // label: 'Select a class',
        showClearButton: true,
        // showSearchBox: true,
        // maxHeight: 450,
        // // popupItemDisabled: (String s) => s.startsWith('I'),
      ));
      formWidget.add(SizedBox(
        height: 24,
      ));
      formWidget.add(Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          ReactiveFormConsumer(
            builder: (context, form, child) {
              return ElevatedButton(
                  child: Text('Cancel'.tr), onPressed: _onCancel);
            },
          ),
          SizedBox(width: 20),
          ReactiveFormConsumer(
            builder: (context, form, child) {
              return ElevatedButton(
                  child: Text('Submit'.tr), onPressed: _onUpdate);
            },
          ),
        ],
      ));
      return formWidget;
    }

    _buildObxForm() {
      return Obx(() {
        // ignore: unused_local_variable
        var teacherCount = controller.teacherItems.length;
        return ReactiveForm(
            formGroup: form, child: Column(children: _buildForm()));
      });
    }

    return AlertDialog(
        title: Text('Move To Other Class'.tr),
        titleTextStyle: TextStyle(
            fontWeight: FontWeight.bold,
            letterSpacing: 1,
            color: Get.isDarkMode ? Color(0xffcccccc) : Colors.black,
            fontSize: 20),
        backgroundColor: Get.isDarkMode
            ? (Color(0xff333333))
            : Color.fromARGB(255, 234, 241, 238),
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(20))),
        content: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Container(
                width: 420,
                height: 160,
                child: Column(children: [_buildObxForm()]))));
  }
}
